<template>
    <ul class="list">
        <li class="item" v-for="item of letters" 
            :key="item" 
            :ref="item"
            @click="handleLetterClick"
            @touchstart="handleTouchStart"
            @touchmove="handleTouchMove"
            @touchend="handleTouchEnd"
        >{{item}}</li>
        
    </ul>
</template>

<script>
export default {
    name:'CityAlphabet',
    props:{
        cities:Object
    },
    computed:{
        letters(){
            const letters = [];
            for (let i in this.cities) {
                letters.push(i)     
            }
            return letters
            
            // 输出如['A','B','C']
        }
    },
    data(){
        return{
            touchStatus:false,
            startY:0,
            timer:null
        }
        
    },
    updated(){
        this.startY = this.$refs['A'][0].offsetTop;
    },
    methods:{
        handleLetterClick(e){
            this.$emit('change',e.target.innerText)//向外触发事件

        },
        handleTouchStart(){
            this.touchStatus = true
        },
        handleTouchMove(e){
            if(this.touchStatus){
                //函数截流，大大节约函数执行的频率，提高网页性能。如果你执行此操作（手指滑动），先把上次执行的操作清除掉，再执行这次操作
                if(this.timer){
                    clearTimeout(this.timer)
                }
                this.timer = setTimeout(() => {
                    // const startY = this.$refs['A'][0].offsetTop;//offsetTop是当前元素顶部距离最近父元素底部的距离
                    const touchY = e.touches[0].clientY - 79;//手指滑动的每个元素距离导航条的距离（79为导航的高）
                    const index = Math.floor((touchY - this.startY) / 20);//滑动到元素的下标
                    if(index >= 0 && index < this.letters.length){
                        this.$emit('change',this.letters[index])
                    }
                },16)
                
            }
        },
        handleTouchEnd(){
            this.touchStatus = false
        }
    }
}
</script>

<style lang="less" scoped>
    @import '~styles/varibles.less';
    .list{
        display: flex;//垂直方向居中
        flex-direction: column;//垂直方向居中
        justify-content: center;//垂直方向居中
        position: absolute;
        top: 1.58rem;
        right: 0;
        bottom: 0;
        width: .4rem;
        .item{
            text-align: center;
            line-height: .4rem;
            color: @bgcolor;
        }
    }
</style>


